package com.lxj.fast_android_demo.view;

import java.lang.reflect.Method;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.lxj.fast_android_demo.R;
import com.lxj.fast_android_demo.dto.DataRecord;
import com.lxj.fast_android_demo.dto.Dataset;
import com.lxj.fast_android_demo.meap_builder.Shell;
import com.lxj.fast_android_demo.util.DatasetUtil;

/**
 * UITable
 * 
 * @author LiangXiangJu
 * @creationTime 2014-7-2 下午6:43:34
 * @version
 */
@SuppressLint("ResourceAsColor")
public class UIMeapTable extends LinearLayout {
	private Context context;
	private Dataset dataset;
	private String tableJson;

	public UIMeapTable(Context context, Dataset dataset, String tableJson) {
		super(context);
		this.context = context;
		this.dataset = dataset;
		this.tableJson = tableJson;
		init();
	}

	public UIMeapTable(Context context, AttributeSet attrs, Dataset dataset,
			String tableJson) {
		super(context, attrs);
		this.context = context;
		this.dataset = dataset;
		this.tableJson = tableJson;
		init();
	}

	public UIMeapTable(Context context, AttributeSet attrs, int defStyle,
			Dataset dataset, String tableJson) {
		super(context, attrs, defStyle);
		this.context = context;
		this.dataset = dataset;
		this.tableJson = tableJson;
		init();
	}

	/**
	 * 初始化
	 * 
	 * @author LiangXiangJu
	 * @creationTime 2014-6-29 下午12:59:03
	 * @version
	 */
	private void init() {
		this.setLayoutParams(new LayoutParams(
				LinearLayout.LayoutParams.MATCH_PARENT,
				LinearLayout.LayoutParams.WRAP_CONTENT));
		this.setOrientation(LinearLayout.VERTICAL);
		this.setBackgroundColor(Color.WHITE);
		ListView lvList = new ListView(context);
		this.addView(lvList);

		lvList.setLayoutParams(new LayoutParams(
				LinearLayout.LayoutParams.MATCH_PARENT,
				LinearLayout.LayoutParams.WRAP_CONTENT));
		ListAdapter adapter = new CustomTableAdapter(dataset.getRecords());
		lvList.setAdapter(adapter);
	}

	class CustomTableAdapter extends BaseAdapter {
		private List<DataRecord> recordList;

		public CustomTableAdapter(List<DataRecord> recordList) {
			this.recordList = recordList;
		}

		@Override
		public int getCount() {
			return recordList.size();
		}

		@Override
		public DataRecord getItem(int arg0) {
			return recordList.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			return arg0;
		}

		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			arg1 = getLayout(tableJson, arg0);
			return arg1;
		}
	}

	/**
	 * 获取table的每行样式
	 * 
	 * @author LiangXiangJu
	 * @creationTime 2014-7-2 下午8:36:08
	 * @version
	 * @param tableJson
	 * @param position
	 * @return
	 */
	private View getLayout(String tableJson, int position) {
		LinearLayout returnLayout = new LinearLayout(context);
		View layout = null;

		if (null != tableJson) {
			try {
				JSONObject jsonObject = new JSONObject(tableJson);
				JSONObject fields = null;
				if (!jsonObject.isNull("fields")) {
					fields = jsonObject.getJSONObject("fields");
				}
				JSONObject layoutJson = jsonObject.getJSONObject("layout");
				layout = parseLayout(layoutJson, fields, position);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		returnLayout.addView(layout);
		return returnLayout;
	}

	/**
	 * 解析layoutJson
	 * 
	 * @author LiangXiangJu
	 * @creationTime 2014-7-2 下午8:35:16
	 * @version
	 * @param layoutJson
	 * @param fields
	 * @param position
	 * @return
	 */
	private View parseLayout(JSONObject layoutJson, JSONObject fields,
			int position) {
		try {
			if ("Liner".equals(layoutJson.get("type"))) {
				LinearLayout lineLayout = new LinearLayout(context);
				if (0 == layoutJson.getInt("orientation")) {
					lineLayout.setOrientation(LinearLayout.HORIZONTAL);
				} else {
					lineLayout.setOrientation(LinearLayout.VERTICAL);
				}
				// LinearLayout样式
				if (!layoutJson.isNull("style")) {
					JSONObject styleJson = layoutJson.getJSONObject("style");
					if (!styleJson.isNull("padding")) {
						lineLayout.setPadding(
								styleJson.getJSONObject("padding").getInt(
										"left"),
								styleJson.getJSONObject("padding")
										.getInt("top"),
								styleJson.getJSONObject("padding").getInt(
										"right"),
								styleJson.getJSONObject("padding").getInt(
										"bottom"));
					}
					lineLayout.setLayoutParams(parseLayoutParams(
							layoutJson.getJSONObject("style"), position));
				}

				// LinearLayout子控件
				if (!layoutJson.isNull("contents")) {
					JSONArray contentArray = layoutJson
							.getJSONArray("contents");
					for (int i = 0; i < contentArray.length(); i++) {
						JSONObject childJson = contentArray.getJSONObject(i);
						if (!childJson.isNull("fieldId")) {
							TextView tv = new TextView(context);
							lineLayout.addView(tv);
							// 默认设置textView的gravity为center
							tv.setGravity(Gravity.CENTER);

							// TextView样式
							if (!childJson.isNull("style")) {
								JSONObject styleJson = childJson
										.getJSONObject("style");
								if (!styleJson.isNull("padding")) {
									tv.setPadding(
											styleJson.getJSONObject("padding")
													.getInt("left"), styleJson
													.getJSONObject("padding")
													.getInt("top"), styleJson
													.getJSONObject("padding")
													.getInt("right"), styleJson
													.getJSONObject("padding")
													.getInt("bottom"));
								}
								tv.setLayoutParams(parseLayoutParams(styleJson,
										position));
								if (!styleJson.isNull("font")) {
									TextPaint tp = tv.getPaint();
									JSONObject fontJson = styleJson
											.getJSONObject("font");
									if (!fontJson.isNull("size")) {
										tv.setTextSize(
												TypedValue.COMPLEX_UNIT_SP,
												fontJson.getInt("size"));
									}
									if (!fontJson.isNull("family")) {
										// 常规字体类型 Typeface.DEFAULT
										// 黑体字体类型 Typeface.DEFAULT_BOLD
										// 等宽字体类型 Typeface.MONOSPACE
										// sans serif字体类型 Typeface.SANS_SERIF
										// serif字体类型 Typeface.SERIF

										// 字体风格
										// 粗体 Typeface.BOLD
										// 粗斜体 Typeface.BOLD_ITALIC
										// 斜体 Typeface.ITALIC
										// 常规 Typeface.NORMAL

										// 类型和风格 (斜体没有效果)
										tp.setTypeface(Typeface.create(
												Typeface.SANS_SERIF,
												Typeface.BOLD_ITALIC));
									}
									if (!fontJson.isNull("weight")) {
										if ("bold".equals(fontJson
												.getString("weight"))) {
											tp.setFakeBoldText(true);
										} else if ("italic".equals(fontJson
												.getString("weight"))) {
											// float类型参数，负数表示右斜，整数左斜
											tp.setTextSkewX(-0.5f);
											// tp.setUnderlineText(true);
											// true为下划线，false为非下划线
											// tp.setStrikeThruText(true);
											// true为删除线，false为非删除线
										}
									}
									if (!fontJson.isNull("color")) {
										// tp设置颜色值无效,textView直接设置
										String colorStr = fontJson
												.getString("color");
										if (!DatasetUtil.isStrEmpty(colorStr)) {
											if (colorStr.startsWith("#")) {
												tv.setTextColor(Color
														.parseColor(colorStr));
											} else {
												// color指定方法
												Object colorObj = invokeMethod(
														colorStr, position);
												if (null != colorObj) {
													tv.setTextColor((Integer) colorObj);
												}
											}
										}
									}
								}
							}

							// textView赋值
							if (null != fields) {
								JSONObject fieldJson = fields
										.getJSONObject(childJson
												.getString("fieldId"));

								dataset.goToIndex_(position);
								if ("empName".equals(fieldJson
										.getString("dataIndex"))) {
									tv.setBackgroundResource(R.drawable.c7);
								} else if ("empGener".equals(fieldJson
										.getString("dataIndex"))) {
									tv.setBackgroundResource(R.drawable.c10);
								} else if ("empAge".equals(fieldJson
										.getString("dataIndex"))) {
									tv.setBackgroundResource(R.drawable.c3);
								} else if ("memo".equals(fieldJson
										.getString("dataIndex"))) {
									tv.setBackgroundResource(R.drawable.c4);
								}
								tv.setText(dataset.getValue(fieldJson
										.getString("dataIndex")));
							}
						}
						// 嵌套layout
						else {
							lineLayout.addView(parseLayout(childJson, fields,
									position));
						}
					}
				}
				return lineLayout;
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 解析样式
	 * 
	 * @author LiangXiangJu
	 * @creationTime 2014-7-4 下午2:45:48
	 * @version
	 * @param styleJson
	 * @param position
	 * @return
	 */
	private LinearLayout.LayoutParams parseLayoutParams(JSONObject styleJson,
			int position) {
		LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.WRAP_CONTENT,
				LinearLayout.LayoutParams.WRAP_CONTENT);
		try {
			if (!styleJson.isNull("size")) {
				// 解析宽度
				String layoutWidth;
				layoutWidth = styleJson.getJSONObject("size")
						.getString("width");

				if (DatasetUtil.isNumberData(layoutWidth)) {
					layoutParams.width = DatasetUtil.forceParseInt(layoutWidth);
				} else {
					int widthValue = 0;
					if (!DatasetUtil.isStrEmpty(layoutWidth)) {
						Object widthObj = invokeMethod(layoutWidth, position);
						if (null != widthObj) {
							widthValue = ((Integer) widthObj);
						}
					}
					layoutParams.width = widthValue;
				}

				// 解析高度
				String layoutHeight = styleJson.getJSONObject("size")
						.getString("height");
				if (DatasetUtil.isNumberData(layoutHeight)) {
					layoutParams.height = DatasetUtil
							.forceParseInt(layoutHeight);
				} else {
					int heightValue = 0;
					if (!DatasetUtil.isStrEmpty(layoutHeight)) {
						Object heightObj = invokeMethod(layoutHeight, position);
						if (null != heightObj) {
							heightValue = ((Integer) heightObj);
						}
					}
					layoutParams.height = heightValue;
				}
			}
			if (!styleJson.isNull("margin")) {
				layoutParams.setMargins(styleJson.getJSONObject("margin")
						.getInt("left"), styleJson.getJSONObject("margin")
						.getInt("top"), styleJson.getJSONObject("margin")
						.getInt("right"), styleJson.getJSONObject("margin")
						.getInt("bottom"));
			}
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		return layoutParams;
	}

	/**
	 * builder方法调用
	 * 
	 * @author LiangXiangJu
	 * @creationTime 2014-7-4 下午4:45:02
	 * @version
	 * @param methodName
	 * @param position
	 * @return
	 */
	private Object invokeMethod(String methodName, int position) {
		Method method;
		try {
			method = Shell.class
					.getMethod(methodName, Dataset.class, int.class);
			return method.invoke(this, dataset, position);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
